import './index.less';
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Button, Card, Divider, Form, Space, FormInstance, Input, message, Modal, Row, Table, Select } from 'antd';
import { ResponseData } from '@/utils/request';
import { createArticle, detailData, queryUserList, removeData, updateData as updateDataService } from './service';
import { PaginationConfig, TableListItem, IResponseData } from './data.d';

import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { ColumnsType } from 'antd/lib/table';

function App() {
  // 获取数据
  const [loading, setLoading] = useState<boolean>(false);
  const [list, setList] = useState<TableListItem[]>([]);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState<PaginationConfig>({
    total: 0,
    current: 1,
    pageSize: 10,
    showSizeChanger: true,
    showQuickJumper: true,
  });
  const getList = async (params?: pagination): Promise<void> => {
    // setLoading(true);

    const response: ResponseData<IResponseData> = await queryUserList({
      // ...params,
      page: pagination.current,
      size: 10,
    });
    const data = response.data || { list: [], total: 0 };
    console.log(data, 'data22')
    setList(data || []);
    // setPagination({
    //   ...pagination,
    //   current,
    //   total: data.total || 0,
    // });

    setLoading(false);
  };
  useEffect(() => {
    getList();
  }, []);

  // 删除
  const [deleteLoading, setDeleteLoading] = useState<number[]>([]);
  const deleteTableData = (id: number) => {
    Modal.confirm({
      title: '删除',
      content: '确定删除吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        setDeleteLoading([id]);
        await removeData(id);
        message.success('删除成功！');
        getList({curPage: pagination.current});
        setDeleteLoading([]);
      },
    });
  };

  // 编辑弹框 data - 详情
  const [updateSubmitLoading, setUpdateSubmitLoading] = useState<boolean>(false);
  const [updateFormVisible, setUpdateFormVisible] = useState<boolean>(false);
  const [updateData, setUpdateData] = useState<Partial<TableListItem>>({});
  const [detailUpdateLoading, setDetailUpdateLoading] = useState<number[]>([]);
  const detailUpdateData = async (id: number) => {
    setDetailUpdateLoading([id]);

    const response: ResponseData<TableListItem> = await detailData(id);
    const { data } = response;
    setUpdateData({
      ...data,
    });
    setUpdateFormVisible(true);

    setDetailUpdateLoading([]);
  };

  const updataFormCancel = async () => {
    setUpdateData({});
    setUpdateFormVisible(false);
  };

  const updateSubmit = async (values: TableListItem) => {
    setUpdateSubmitLoading(true);

    const { id, ...params } = values;
    await updateDataService(id, { ...params });
    updataFormCancel();
    message.success('编辑成功！');
    getList({current: pagination.current});

    setUpdateSubmitLoading(false);
  };

  // 新增
  const [createSubmitLoading, setCreateSubmitLoading] = useState<boolean>(false);
  const [createFormVisible, setCreateFormVisible] = useState<boolean>(false);
  const createSubmit = async (values: Omit<TableListItem, 'id'>, form: FormInstance) => {
    setCreateSubmitLoading(true);

    await createArticle(values);
    form.resetFields();
    setCreateFormVisible(false);
    message.success('新增成功！');
    getList({current: 1});

    setCreateSubmitLoading(false);
  };


  
  const ARTICLETYPE = {
    PUBLIC_3: '公开',
  };
  const columns: ColumnsType<TableListItem> = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      render: (_, record, index) => <>{(pagination.current - 1) * pagination.pageSize + index + 1}</>,
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
    },
    {
      title: '头像',
      dataIndex: 'imgs',
      render: val => <img style={{ width: '50px', height: '50px'}} src={val} />
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },
    {
      title: '年龄',
      dataIndex: 'age',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      render: (val, record, index) => <>{val == 0 ? '女' : '男'}</>,
    },
    {
      title: '用户类型',
      dataIndex: 'type',
      render: (val, record, index) => <>{val == 0 ? '买家' : '卖家'}</>,
    },
    {
      title: '简介',
      dataIndex: 'context',
      render: val => val || '-'
    },
    // {
    //   title: '操作',
    //   key: 'action',
    //   width: 240,
    //   render: (_, record) => (
    //     <>
    //       <Button
    //         type='link'
    //         loading={detailUpdateLoading.includes(record.id)}
    //         onClick={() => detailUpdateData(record.id)}
    //       >
    //         详情
    //       </Button>
    //       <Button
    //         type='link'
    //         loading={detailUpdateLoading.includes(record.id)}
    //         onClick={() => detailUpdateData(record.id)}
    //       >
    //         编辑
    //       </Button>
    //       <Button type='link' loading={deleteLoading.includes(record.id)} onClick={() => deleteTableData(record.id)}>
    //         删除
    //       </Button>
    //     </>
    //   ),
    // },
  ];

  return (
    <div className='layout-main-conent'>
      <Card>
        <div className='search'>
          <Form form={form} name='advanced_search' className='search-form' onFinish={() => console.log(1)}>
            <Row gutter={24}>
              <Form.Item name='nickname' label='昵称'>
                <Input placeholder='请输入' />
              </Form.Item>
              {/* <Form.Item name='title' label='标题'>
                <Input placeholder='请输入' />
              </Form.Item>
              <Form.Item name='articleType' label='文章类型'>
                <Select
                  placeholder='请选择'
                  allowClear
                  style={{ width: 160 }}
                  options={[
                    { value: '0', label: '女' },
                    { value: '1', label: '男' },
                  ]}
                />
              </Form.Item> */}
            </Row>
            <div style={{ textAlign: 'right' }}>
              <Space size='small'>
                <Button type='primary' htmlType='submit' onClick={() => {
                    const params = form.getFieldsValue()
                    getList(params)
                  }}>
                  查询
                </Button>
                <Button
                  onClick={() => {
                    form.resetFields();
                    getList()
                  }}
                >
                  重置
                </Button>
              </Space>
            </div>
          </Form>
        </div>
        <Table
          rowKey='id'
          columns={columns}
          dataSource={list}
          loading={loading}
          pagination={{
            ...pagination,
            onChange: (page: number) => {
              getList({curPage: page});
            },
          }}
        />
      </Card>
    </div>
  );
}

export default App;
